<template>
  <CommonDateSearch ref="searchRef2" @search="handleSearch" />
  <div class="sub-content-box" v-loading="loading">
    <div style="width: 100%;text-align: right;margin-right: 15px;"> <a-button type="primary" @click="handleExport"
        :loading="exportLoading">导出</a-button></div>


    <!-- 左侧折线图区域 -->
    <div class="column-box">
      <div class="chart-box" v-for="item in lineTypeList" :key="item.dictCode">
        <Line style="height: 350px;" :loading="item.loading" :chartData="item.chartData" :title="item.itemName"
          @ready="handleChartReady(item.dictCode)" />
      </div>
    </div>

    <!-- 右侧饼图区域 -->
    <div class="column-box">
      <div class="chart-box" v-for="(item, index) in pieTypeList" :key="item.dictCode">
        <Pie v-if="pieTypeList.length > 0" style="height: 350px;" :loading="item.loading" :chartData="item.chartData"
          :title="`${item.itemName}占比分析`" @ready="handleChartReady(item.dictCode)" />
      </div>
    </div>

  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick, computed, onUnmounted } from 'vue'
import Pie from '@/components/Charts/Pie/index.vue'
import Line from '@/components/Charts/Line/index.vue'
import { getChartChildListData, getPieChartChildListData } from '@/api/common/chart'
import { getDictListByCode } from '@/api/sys/dict'
import CommonDateSearch from './CommonDateSearch.vue'
import { GeneralExportData } from '@/api/common/chart.ts'
import { downloadByData } from '@/utils/file/download'
import { message } from 'ant-design-vue'

defineOptions({ name: 'Detail2' })

// 搜索参数
const searchRef2 = ref()
const searchInfo = ref()

// 图表数据
const dictCode = 'energy_consumption_of_air_conditioning_system2'
const lineTypeList = ref([])
const pieTypeList = ref([])

// 图表渲染状态
const chartsReady = ref({})
const isFirstLoad = ref(true)

// 加载状态
const dataReady = ref(false)
const exportLoading = ref(false)

// 计算属性：整体加载状态
const loading = computed(() => {
  return !dataReady.value ||
    lineTypeList.value.some(item => item.loading) ||
    pieTypeList.value.some(item => item.loading)
})

// 导出功能
const handleExport = async () => {
  if (!searchInfo.value) return

  exportLoading.value = true
  try {
    searchInfo.value.dictCode = "energy_consumption_of_air_conditioning_system2"
    searchInfo.value.itemName = "能源消耗明细"

    const { data, headers } = await GeneralExportData(searchInfo.value)
    const contentDisposition = decodeURIComponent(headers["content-disposition"])
    const filenameMatch = contentDisposition.match(/filename\*=UTF-8''(.+)|filename="(.+)"|filename=(.+)/)
    const fileName = filenameMatch[1] || filenameMatch[2] || filenameMatch[3]

    downloadByData(data, fileName)
    message.success("导出成功")
  } catch (error) {
    console.error('导出失败', error)
    message.error("导出失败，请重试")
  } finally {
    exportLoading.value = false
  }
}

// 初始化数据
onMounted(async () => {
  await getTypeList()
  searchRef2.value.handleSearch()

  // 监听窗口大小变化，调整图表
  window.addEventListener('resize', handleWindowResize)
})

// 获取字典列表
const getTypeList = async () => {
  try {
    const res = await getDictListByCode(dictCode)

    // 初始化图表数据结构
    lineTypeList.value = res.map((item) => ({
      ...item,
      loading: true,
      chartData: []
    }))

    pieTypeList.value = res.map((item) => ({
      ...item,
      loading: true,
      chartData: []
    }))

    dataReady.value = true
  } catch (error) {
    // console.error('获取字典列表失败', error)
    // message.error("数据加载失败，请刷新页面")
  }
}

// 处理搜索
const handleSearch = async (params) => {
  if (!dataReady.value) {
    // 等待数据结构准备好
    setTimeout(() => handleSearch(params), 300)
    return
  }

  searchInfo.value = params

  // 显示加载状态
  lineTypeList.value.forEach(item => item.loading = true)
  pieTypeList.value.forEach(item => item.loading = true)

  // 重置图表状态
  chartsReady.value = {}
  isFirstLoad.value = true

  // 并行加载所有图表数据
  try {
    await Promise.all([
      getLineChartData(params),
      getPieChartData(params)
    ])

    // 确保DOM更新后重绘图表
    await nextTick()

    // 首次加载时强制重绘所有图表
    if (isFirstLoad.value) {
      isFirstLoad.value = false
      handleWindowResize()
    }
  } catch (error) {
    // console.error('获取图表数据失败', error)
    // message.error("图表加载失败")
  }
}

// 监听搜索参数变化
// watch(
//   () => searchInfo,
//   (newValue) => {
//     if (Object.values(newValue).length > 0) {
//       handleSearch(newValue)
//     }
//   },
//   { immediate: true }
// )

// 获取折线图数据
const getLineChartData = async (searchInfo) => {
  const requests = lineTypeList.value.map(item => {
    return getChartChildListData({
      ...searchInfo,
      dictCode,
      itemName: item.itemName
    }).then(res => {
      item.chartData = res
      return item
    }).catch(error => {
      // console.error(`获取${item.itemName}数据失败`, error)
      return item
    }).finally(() => {
      item.loading = false
    })
  })

  await Promise.all(requests)
}

// 获取饼图数据
const getPieChartData = async (searchInfo) => {
  const requests = pieTypeList.value.map(item => {
    return getPieChartChildListData({
      ...searchInfo,
      dictCode,
      itemName: item.itemName
    }).then(res => {
      // 格式化饼图标签
      res.forEach(item => {
        item.label = {
          formatter: function (data) {
            return `${data.name} (${data.percent.toFixed(0)}%)`
          }
        }
      })

      item.chartData = res
      return item
    }).catch(error => {
      // console.error(`获取${item.itemName}饼图数据失败`, error)
      return item
    }).finally(() => {
      item.loading = false
    })
  })

  await Promise.all(requests)
}

// 处理图表准备就绪事件
const handleChartReady = (key) => {
  chartsReady.value[key] = true

  // 当所有图表都准备好且是首次加载时，执行一次强制重绘
  if (Object.keys(chartsReady.value).length === lineTypeList.value.length + pieTypeList.value.length && isFirstLoad.value) {
    isFirstLoad.value = false
    handleWindowResize()
  }
}

// 处理窗口大小变化
const handleWindowResize = () => {
  // 触发所有图表重新计算尺寸
  const chartElements = document.querySelectorAll('.chart-container')
  chartElements.forEach(el => {
    if (el.__chart__) {
      el.__chart__.resize()
    }
  })
}

// 组件销毁时移除事件监听
onUnmounted(() => {
  window.removeEventListener('resize', handleWindowResize)
})
</script>

<style scoped lang="scss">
.sub-content-box {
  display: flex;
  flex-wrap: wrap;
  height: auto;
  /* overflow: auto; */

  .column-box {
    width: 50%;
    height: 100%;
  }

  .chart-box {
    /* flex-shrink: 0; */

    /* width: calc(100% / 3); */
    height: 32%;
    padding: 4px;
  }
}
</style>